﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using ACP.Business;
using ACP.DTO;
using System.Web.Security;

namespace ACP.Web.UI.admin
{
    public partial class Questions : System.Web.UI.Page
    {
        Panel pnlDropDownList;
        protected void Page_Init(object sender, EventArgs e)
        {
            //Recreate Controls
            string ctrlname = Page.Request.Params["__EVENTTARGET"];
            if (ctrlname != null && ctrlname != String.Empty)
            {
                //control = Page.FindControl(ctrlname);
                if(ctrlname.Contains("ddlTopics"))
                    CreateTopicsDropdown();
            }
            //else
            //{
            //    CreateTopicsDropdown();
            //}
            //CreateSubTopicsDropdown();
                //RecreateControls("ddlDynamic", "DropDownList");
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                // System.Web.Security.MembershipUser user = Membership.GetUser();
                // if (user != null)
                // {
                // string[] adminusers = ConfigurationManager.AppSettings["adminusers"].ToLower().Split('|');
                // Session["userName"] = user.UserName.ToLower(); //TBD
                // bool booluserExist = adminusers.Contains(Convert.ToString(Session["userName"]));
                //if (booluserExist)
                // {
                bindExamTypes();
               
                // }
                //else
                // {
                // Response.Redirect("~/Default.aspx", false);
                // }
                // }
                // else
                // {
                // Response.Redirect("~/Default.aspx", false);
                // }
            }
            
           
        }

        private void bindExamTypes()
        {
            try
            {
                ddlExampType.DataSource = ExamTypeLogic.GetExaminationsTypes();
                ddlExampType.DataTextField = "examname";
                ddlExampType.DataValueField = "examid";
                ddlExampType.DataBind();

                ddlExampType.Items.Insert(0, new ListItem("Select", "0"));
            }
            catch (Exception ex)
            {
                acptest_ErrorLog errorLog = new acptest_ErrorLog()
                {
                    ErrorMessage = ex.Message,
                    ErrorFunction = "bindExamTypes",
                    InsertedTime = DateTime.Now,
                    ModuleName = "Questions.aspx"
                };
                ACPErrorLogLogic.ErrorLog(errorLog);
            }

        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                question newQuestion = new question()
                {
                    examid = Convert.ToInt32(ddlExampType.SelectedValue),
                    questiontype = ddlChoiceType.SelectedValue,
                    question1 = txtQuestion.Text,
                    option1 = txtOption1.Text,
                    option2 = txtOption2.Text,
                    option3 = txtOption3.Text,
                    option4 = txtOption4.Text,
                    description = txtDescription.Text,
                    answer = txtAnswer.Text,
                    uploadedby = "Kishore", //TBD
                    complexity = ddlComplexity.SelectedValue,
                    issample = ddlQuestionType.SelectedValue == "1" ? true : false,
                    referenceid = 1, //TBD
                    status = true,
                    topicId = Session["SelectedTopic"] != null ? Convert.ToInt32(Session["SelectedTopic"]) : 0,
                    uploadeddate = DateTime.Now
                };
                QuestionsLogic.InsertQuestion(newQuestion);
                ResetControls();
            }
            catch (Exception ex)
            {
                acptest_ErrorLog errorLog = new acptest_ErrorLog()
                {
                    ErrorMessage = ex.Message,
                    ErrorFunction = "bindDropdowns",
                    InsertedTime = DateTime.Now,
                    ModuleName = "Questions.aspx"
                };
                ACPErrorLogLogic.ErrorLog(errorLog);
            }
        }

        protected void btnAddAnother_Click(object sender, EventArgs e)
        {
            try
            {
                question newQuestion = new question()
                {
                    examid = Convert.ToInt32(ddlExampType.SelectedValue),
                    questiontype = ddlChoiceType.SelectedValue,
                    question1 = txtQuestion.Text,
                    option1 = txtOption1.Text,
                    option2 = txtOption2.Text,
                    option3 = txtOption3.Text,
                    option4 = txtOption4.Text,
                    description = txtDescription.Text,
                    answer = txtAnswer.Text,
                    uploadedby = "Kishore", //TBD
                    complexity = ddlComplexity.SelectedValue,
                    issample = ddlQuestionType.SelectedValue == "1" ? true : false,
                    referenceid = 1, //TBD
                    status = true,
                    topicId = Session["SelectedTopic"] != null ? Convert.ToInt32(Session["SelectedTopic"]) : 0,
                    uploadeddate = DateTime.Now
                };
                QuestionsLogic.InsertQuestion(newQuestion);
                ResetControls();
            }
            catch (Exception ex)
            {
                acptest_ErrorLog errorLog = new acptest_ErrorLog()
                {
                    ErrorMessage = ex.Message,
                    ErrorFunction = "bindDropdowns",
                    InsertedTime = DateTime.Now,
                    ModuleName = "Questions.aspx"
                };
                ACPErrorLogLogic.ErrorLog(errorLog);
            }
        }
        protected void btnReset_Click(object sender, EventArgs e)
        {
            ResetControls();
        }

        private void ResetControls()
        {
            ddlExampType.SelectedIndex = 0;
            ddlQuestionType.SelectedIndex = 0;
            txtQuestion.Text = string.Empty;
            txtOption1.Text = string.Empty;
            txtOption2.Text = string.Empty;
            txtOption3.Text = string.Empty;
            txtOption4.Text = string.Empty;
            txtDescription.Text = string.Empty;
            txtAnswer.Text = string.Empty;
            ddlComplexity.SelectedIndex = 0;
            ddlChoiceType.SelectedIndex = 0;
        }

        protected void ddlExampType_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                int examId = Convert.ToInt32(ddlExampType.SelectedValue);

                //Get Parent Topics from DB based on ExamId(i.e. ACP or PMP etc.)
                List<Topic> lstParentTopics = TopicsLogic.GetTopics(t => t.ParentTopicID == null && t.examid == examId && t.status == true);
                List<TopicsDropdowns> lstTopicsDropdowns = null;

                if (lstParentTopics != null)
                {
                    lstTopicsDropdowns = new List<TopicsDropdowns>(); 
                    TopicsDropdowns tpsDDl = new TopicsDropdowns()
                    {
                        PnlDropdownID = "pnlTopics_1",
                        DropdownID = "ddlTopics_1",
                        DdlTopics = lstParentTopics,
                        SelectedTopic = "0"
                    };
                    lstTopicsDropdowns.Add(tpsDDl);
                    Session["TopicsDropdowns"] = lstTopicsDropdowns;
                   // CreateTopicsDropdown();
                    CreateSubTopicsDropdown(lstTopicsDropdowns);
                   
                }
            }
            catch (Exception ex)
            {
                acptest_ErrorLog errorLog = new acptest_ErrorLog()
                {
                    ErrorMessage = "Message: " + ex.Message + " -- StrackTrace: " + ex.StackTrace,
                    ErrorFunction = "ddlExampType_SelectedIndexChanged",
                    InsertedTime = DateTime.Now,
                    ModuleName = "Questions.aspx"
                };
                ACPErrorLogLogic.ErrorLog(errorLog);
            }
        }

        private void CreateTopicsDropdown()
        {
            try
            {
                if (Session["TopicsDropdowns"] != null)
                {
                    if (pnlTopics != null) pnlTopics.Controls.Clear();
                    //if (pnlDropDownList != null) pnlDropDownList.Controls.Clear();
                    pnlDropDownList = new Panel();
                    
                    List<TopicsDropdowns> lstTopicsDropdowns = (List<TopicsDropdowns>)Session["TopicsDropdowns"];
                    foreach (var item in lstTopicsDropdowns)
                    {
                        Panel pnlDropdown = new Panel();
                        pnlDropdown.ID = item.PnlDropdownID;
                        Literal ltrlDDlLabel = new Literal();
                        ltrlDDlLabel.Text = "Select Topic &nbsp;";

                        Literal ltrlBreak = new Literal();
                        ltrlBreak.Text = "<br/><br/>";

                        DropDownList ddl = new DropDownList();
                        ddl.ID = item.DropdownID;

                        if (item.DdlTopics != null)
                        {
                            ddl.DataSource = item.DdlTopics;
                            ddl.DataValueField = "TopicId";
                            ddl.DataTextField = "TopicTitle";
                            ddl.DataBind();
                        }
                        ddl.Items.Insert(0, new ListItem("Select", "0"));
                        ddl.Enabled = ddl.Items.Count > 1 ? true : false;
                        ddl.SelectedValue = item.SelectedTopic != null ? item.SelectedTopic : "0";
                        ddl.AutoPostBack = true;
                        ddl.SelectedIndexChanged += new EventHandler(ddl_SelectedIndexChanged);
                        pnlDropdown.Controls.Add(ltrlDDlLabel);
                        pnlDropdown.Controls.Add(ddl);
                        pnlDropdown.Controls.Add(ltrlBreak);
                        pnlDropDownList.Controls.Add(pnlDropdown);
                        if (pnlTopics != null) pnlTopics.Controls.Add(pnlDropDownList);
                    }

                }
            }
            catch (Exception ex)
            {
                acptest_ErrorLog errorLog = new acptest_ErrorLog()
                {
                    ErrorMessage = "Message: " + ex.Message + " -- StrackTrace: " + ex.StackTrace,
                    ErrorFunction = "CreateTopicsDropdown",
                    InsertedTime = DateTime.Now,
                    ModuleName = "Questions.aspx"
                };
                ACPErrorLogLogic.ErrorLog(errorLog);
            }
        }
        private void CreateSubTopicsDropdown(List<TopicsDropdowns> lstTopicsDropdowns)
        {
            try
            {
                if (Session["TopicsDropdowns"] != null)
                {
                    //if (pnlTopics != null) pnlTopics.Controls.Clear();
                    if (pnlDropDownList == null) pnlDropDownList = new Panel();
                    //List<TopicsDropdowns> lstTopicsDropdowns = (List<TopicsDropdowns>)Session["TopicsDropdowns"];
                    TopicsDropdowns tpsDDl = lstTopicsDropdowns.Count > 1 ? lstTopicsDropdowns.LastOrDefault() : lstTopicsDropdowns.FirstOrDefault();
                    //foreach (var item in lstTopicsDropdowns)
                   // {
                        Panel pnlDropdown = new Panel();
                        pnlDropdown.ID = tpsDDl.PnlDropdownID;

                        Literal ltrlDDlLabel = new Literal();
                        ltrlDDlLabel.Text = "Select Topic &nbsp;";

                        Literal ltrlBreak = new Literal();
                        ltrlBreak.Text = "<br/><br/>";

                        DropDownList ddl = new DropDownList();
                        ddl.ID = tpsDDl.DropdownID;

                        if (tpsDDl.DdlTopics != null)
                        {
                            ddl.DataSource = tpsDDl.DdlTopics;
                            ddl.DataValueField = "TopicId";
                            ddl.DataTextField = "TopicTitle";
                            ddl.DataBind();
                        }
                        ddl.Items.Insert(0, new ListItem("Select", "0"));
                        ddl.Enabled = ddl.Items.Count > 1 ? true : false;
                        ddl.SelectedValue = tpsDDl.SelectedTopic != null ? tpsDDl.SelectedTopic : "0";
                        ddl.AutoPostBack = true;
                        ddl.SelectedIndexChanged += new EventHandler(ddl_SelectedIndexChanged);
                        pnlDropdown.Controls.Add(ltrlDDlLabel);
                        pnlDropdown.Controls.Add(ddl);
                        pnlDropdown.Controls.Add(ltrlBreak);
                        pnlDropDownList.Controls.Add(pnlDropdown);
                        if (pnlTopics.Controls.IndexOf(pnlDropDownList)==-1) pnlTopics.Controls.Add(pnlDropDownList);
                   // }

                }
            }
            catch (Exception ex)
            {
                acptest_ErrorLog errorLog = new acptest_ErrorLog()
                {
                    ErrorMessage = "Message: " + ex.Message + " -- StrackTrace: " + ex.StackTrace,
                    ErrorFunction = "CreateTopicsDropdown",
                    InsertedTime = DateTime.Now,
                    ModuleName = "Questions.aspx"
                };
                ACPErrorLogLogic.ErrorLog(errorLog);
            }
        }

        void ddl_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                DropDownList ddl = (DropDownList)sender;
                int ddlSelectedValue = Convert.ToInt32(ddl.SelectedValue);

                Session["SelectedTopic"] = ddlSelectedValue;

                List<Topic> lstParentTopics = TopicsLogic.GetTopics(t => t.ParentTopicID == ddlSelectedValue && t.status == true);

                if (lstParentTopics != null && Session["TopicsDropdowns"] !=null)
                {
                    List<TopicsDropdowns> lstTopicsDropdowns = (List<TopicsDropdowns>)Session["TopicsDropdowns"];
                    //Set Exisitng dropdown Selected Value
                   TopicsDropdowns existingTpsDDl =  lstTopicsDropdowns.Where(d=>d.DropdownID.Contains(ddl.ID)).FirstOrDefault();

                   int selectedDdlIndex = lstTopicsDropdowns.FindIndex(t => t.DropdownID.Contains(ddl.ID));
                   int totalDdlCount = lstTopicsDropdowns.Count-1;

                   if (totalDdlCount > selectedDdlIndex)
                   {
                       //lstTopicsDropdowns.RemoveRange(selectedDdlIndex + 1, (totalDdlCount - (selectedDdlIndex + 1)));

                       List<TopicsDropdowns> lstRemovedDropdowns = lstTopicsDropdowns.Skip(selectedDdlIndex + 1).ToList();
                       foreach (var item in lstRemovedDropdowns)
                       {
                           lstTopicsDropdowns.Remove(item);
                           Panel pnlRemoved = (Panel) pnlDropDownList.FindControl(item.PnlDropdownID);
                           pnlDropDownList.Controls.Remove(pnlRemoved);
                           
                       }
                   }

                   existingTpsDDl.SelectedTopic = ddl.SelectedValue;
                    //Add New Dropdown
                    int controlId = lstTopicsDropdowns.Count + 1;
                    TopicsDropdowns tpsDDl = new TopicsDropdowns()
                    {
                        PnlDropdownID = "pnlTopics_" + controlId,
                        DropdownID = "ddlTopics_" + controlId,
                        DdlTopics = lstParentTopics,
                        SelectedTopic = "0"
                    };
                    lstTopicsDropdowns.Add(tpsDDl);
                    Session["TopicsDropdowns"] = lstTopicsDropdowns;
                    //CreateTopicsDropdown();
                    CreateSubTopicsDropdown(lstTopicsDropdowns);
                    //if (pnlDropDownList != null) pnlTopics.Controls.Add(pnlDropDownList);
                }
            }
            catch (Exception ex)
            {
                acptest_ErrorLog errorLog = new acptest_ErrorLog()
                {
                    ErrorMessage = "Message: " + ex.Message + " -- StrackTrace: " + ex.StackTrace,
                    ErrorFunction = "ddlExampType_SelectedIndexChanged",
                    InsertedTime = DateTime.Now,
                    ModuleName = "Questions.aspx"
                };
                ACPErrorLogLogic.ErrorLog(errorLog);
            }
        }
    }
}